package org.dant.ant.extension.net.soap;

import java.beans.*;
import java.io.*;
import java.lang.reflect.*;
import org.w3c.dom.*;
import org.apache.soap.util.*;
import org.apache.soap.util.xml.*;
import org.apache.soap.*;
import org.apache.soap.rpc.*;
import org.apache.soap.encoding.soapenc.*;

public class StringBufferSerializer implements Serializer, Deserializer {
  public void marshall(String inScopeEncStyle, Class javaType, Object src,
                       Object context, Writer sink, NSStack nsStack,
                       XMLJavaMappingRegistry xjmr, SOAPContext ctx)
    throws IllegalArgumentException, IOException {

    nsStack.pushScope();

    if ((src != null) && 
        !(src instanceof StringBuffer))
      throw new IllegalArgumentException("Tried to pass a '" +
                        src.getClass().toString() + "' to StringBufferSerializer");

    if (src == null) {

      SoapEncUtils.generateNullStructure(inScopeEncStyle,
                                         javaType,
                                         context,
                                         sink,
                                         nsStack,
                                         xjmr);
    } else {
      StringBuffer sb = (StringBuffer) src; 

      SoapEncUtils.generateStructureHeader(inScopeEncStyle,
                                           javaType,
                                           context,
                                           sink,
                                           nsStack,
                                           xjmr);
      
      sink.write(StringUtils.lineSeparator);
      
      Object value = sb.toString();
      
      xjmr.marshall(Constants.NS_URI_SOAP_ENC, String.class, value,
                    context, sink, nsStack, ctx);
      sink.write(StringUtils.lineSeparator);
    }
    sink.write("</" + context + '>');
    nsStack.popScope();
  }

  public Bean unmarshall(String inScopeEncStyle, QName elementType,
                         Node src, XMLJavaMappingRegistry xjmr,
                         SOAPContext ctx)
    throws IllegalArgumentException {
    Element root = (Element)src;
    String value = DOMUtils.getChildCharacterData(root);
    
    return new Bean(StringBuffer.class, new StringBuffer(value));
  }
}
